package com.cj.common.exception;

import com.cj.common.constant.Constant;
import com.cj.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/7/10 13:33
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class BaseExceptionHander {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = BaseException.class)
    public Result handleBaseException(BaseException e) {
        log.error(e.getMsg());
        e.printStackTrace();
        return Result.error(new Result.CodeMsg(e.getCode(), e.getMsg()));
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFoundException(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.error(new Result.CodeMsg(Constant.SERVICE_FAILED, e.getMessage()));
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.error(new Result.CodeMsg(Constant.SERVICE_FAILED, e.getMessage()));
    }

    @ExceptionHandler(AuthorizationException.class)
    public Result handleAuthorizationException(AuthorizationException e){
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.error(new Result.CodeMsg(Constant.SERVICE_FAILED, e.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.error(new Result.CodeMsg(Constant.SERVICE_FAILED, e.getMessage()));
    }
}

